import React, { useContext, useState } from 'react';
import { DatePicker, Empty, Input, message, Select } from 'antd';
import EmployeeDetailContext from '@/pages/Organization/EmployeeManage/EmployeeDetail/store/context';
import { useDeepCompareEffect } from 'react-use';
import { parseEmployeeExtendInfoList } from '@/pages/Organization/EmployeeManage/components/EmployeeInfoSections/util';
import { defaultFormatResult, useRequest, useDictionary } from '@/hooks';
import CityPicker from '@/components/CityPicker';
import moment from 'moment';
import { getEmployeeFieldConfig } from '@/pages/Organization/EmployeeManage/services';
import FormContainer, { FormItem } from './FormContainer';

/**
 * 员工档案 - 工资社保 - 社保公积金信息
 */
const InsuranceProvidentSection = ({ formData, readonly, saveAction, onChange }) => {
    const employeeDetailContext = useContext(EmployeeDetailContext);
    const currentEmployeeCountryCode = employeeDetailContext?.employeeInfo?.countryNameCode;
    const employeeCode = employeeDetailContext?.employeeInfo?.employeeCode;

    const [socialSecurityList, getSocialSecurityText] = useDictionary('socialSecurity');

    // 因为国际化的字段是在 employeeExtendInfoList 数组里面, 这里将它打散到 formData 里面
    const [parsedFormData, setParsedFormData] = useState();
    // 获取国际化字段的默认配置
    const { data: employeeFieldConfig } = useRequest(
        () => getEmployeeFieldConfig({ countryNameCode: currentEmployeeCountryCode, groupCode: 'insuranceProvident' }),
        {
            ready: !!currentEmployeeCountryCode,
            ...defaultFormatResult
        }
    );

    // mounted
    useDeepCompareEffect(() => {
        const employeeExtendInfoMap = parseEmployeeExtendInfoList(
            formData?.employeeExtendInfoList ?? [],
            currentEmployeeCountryCode
        );
        const combineData = { ...formData, ...employeeExtendInfoMap };
        setParsedFormData(combineData);
    }, [formData]);

    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 保存
    const handleSubmit = async values => {
        // 扩展字段处理
        const employeeExtendInfoList = employeeFieldConfig?.map(item => {
            let fieldValue = values[item.fieldCode];
            // 数据格式转换
            if (fieldValue && ['socialLastYearMonth', 'socialYearMonth'].indexOf(item.fieldCode) > -1) {
                fieldValue = moment(fieldValue).format('YYYY-MM');
            }
            return { ...item, fieldValue };
        });
        const submitData = Object.assign({
            ...formData,
            employeeCode,
            employeeExtendInfoList
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData);
        } else {
            message.error(res.msg);
        }
    };
    return (
        // render
        <FormContainer
            title="社保公积金信息"
            hasEditAuth={!readonly && !!saveAction && !!employeeFieldConfig}
            flexLayout
            onSubmit={handleSubmit}
        >
            {({ getFieldDecorator }) =>
                parsedFormData ? (
                    <>
                        <FormItem
                            label="参保城市"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() =>
                                parsedFormData?.socialCityCode ? (
                                    <CityPicker
                                        valueType="code"
                                        value={parsedFormData?.socialCityCode}
                                        showOnly
                                        filterAreaFn={areaData => areaData?.[0]?.children}
                                    />
                                ) : (
                                    '--'
                                )
                            }
                            // normalComponent={() => <span>{parsedFormData?.socialCityName || '--'}</span>}
                            editComponent={() =>
                                getFieldDecorator('socialCityCode', {
                                    initialValue: parsedFormData?.socialCityCode || '',
                                    rules: [
                                        {
                                            required: true,
                                            message: '参保城市不能为空'
                                        }
                                    ]
                                })(
                                    <CityPicker
                                        valueType="code"
                                        showSearch
                                        placeholder="请选择参保城市"
                                        filterAreaFn={areaData => areaData?.[0]?.children}
                                    />
                                )
                            }
                        />
                        <FormItem
                            label="社保方案"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">
                                    {/* {!!parsedFormData.socialSecurity || parsedFormData.socialSecurity === 0 ? (
                                        <span>
                                            {[
                                                parsedFormData.socialCityName,
                                                getSocialSecurityText(parsedFormData.socialSecurity)
                                            ]
                                                .filter(item => !!item || item === 0)
                                                .join(' - ')}
                                        </span>
                                    ) : (
                                        <span> - </span>
                                    )} */}
                                    {getSocialSecurityText(parsedFormData.socialSecurity) || '--'}
                                </div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('socialSecurity', {
                                    initialValue: parsedFormData?.socialSecurity || undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: '社保方案不能为空'
                                        }
                                    ]
                                })(
                                    <Select placeholder="请选择社保方案">
                                        {socialSecurityList?.map(item => (
                                            <Select.Option value={item.value} key={item.value}>
                                                {item.text}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                )
                            }
                        />
                        <FormItem
                            label="起始缴交月份"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData.socialYearMonth || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('socialYearMonth', {
                                    initialValue:
                                        parsedFormData?.socialYearMonth && parsedFormData?.socialYearMonth !== ''
                                            ? moment(parsedFormData?.socialYearMonth)
                                            : undefined,
                                    rules: [
                                        {
                                            required: true,
                                            message: '起始缴交月份不能为空'
                                        }
                                    ]
                                })(
                                    <DatePicker.MonthPicker
                                        format="YYYY-MM"
                                        style={{ width: '100%' }}
                                        placeholder="请选择起始缴交月份"
                                    />
                                )
                            }
                        />
                        <FormItem
                            label="最近缴交月份"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => parsedFormData.socialLastYearMonth || '--'}
                            editComponent={() =>
                                getFieldDecorator('socialLastYearMonth', {
                                    initialValue:
                                        parsedFormData?.socialLastYearMonth &&
                                        parsedFormData?.socialLastYearMonth !== ''
                                            ? moment(parsedFormData?.socialLastYearMonth)
                                            : undefined
                                })(
                                    <DatePicker.MonthPicker
                                        format="YYYY-MM"
                                        style={{ width: '100%' }}
                                        placeholder="请选择最近缴交月份"
                                    />
                                )
                            }
                        />
                        <FormItem
                            label="原公司名称"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">{parsedFormData.originalCompanyName || '--'}</div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('originalCompanyName', {
                                    initialValue: parsedFormData?.originalCompanyName ?? ''
                                })(<Input placeholder="请填写原公司名称" allowClear maxLength={100} />)
                            }
                        />
                        <FormItem
                            label="原公司公积金账号"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">
                                    {parsedFormData.originalCompanyProvidentFundAccount || '--'}
                                </div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('originalCompanyProvidentFundAccount', {
                                    initialValue: parsedFormData?.originalCompanyProvidentFundAccount ?? ''
                                })(<Input placeholder="请填写原公司公积金账号" allowClear maxLength={100} />)
                            }
                        />
                        <FormItem
                            label="个人公积金账号"
                            show={currentEmployeeCountryCode === 'CN'}
                            normalComponent={() => (
                                <div className="multiLineText">
                                    {parsedFormData.personalProvidentFundAccount || '--'}
                                </div>
                            )}
                            editComponent={() =>
                                getFieldDecorator('personalProvidentFundAccount', {
                                    initialValue: parsedFormData?.personalProvidentFundAccount ?? ''
                                })(<Input placeholder="请填写个人公积金账号" allowClear maxLength={100} />)
                            }
                        />
                    </>
                ) : (
                    <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                )
            }
        </FormContainer>
    );
};

export default InsuranceProvidentSection;
